package cn.yuanqiao.archive.liyong.service.impl;

import cn.yuanqiao.archive.appManager.domain.TenantCategory;
import cn.yuanqiao.archive.appManager.domain.TenantYqda;
import cn.yuanqiao.archive.appManager.domain.TenantYqdaDocument;
import cn.yuanqiao.archive.appManager.domain.YqSy;
import cn.yuanqiao.archive.appManager.mapper.TenantCategoryMapper;
import cn.yuanqiao.archive.appManager.mapper.TenantYqdaDocumentMapper;
import cn.yuanqiao.archive.appManager.service.ITenantSysConfigService;
import cn.yuanqiao.archive.appManager.service.IYqSyService;
import cn.yuanqiao.archive.liyong.domain.TenantDownloadRecord;
import cn.yuanqiao.archive.liyong.domain.vo.DownloadRecord;
import cn.yuanqiao.archive.liyong.mapper.TenantDownloadRecordMapper;
import cn.yuanqiao.archive.liyong.service.TenantDownloadRecordSerive;
import cn.yuanqiao.archive.utils.FileWaterMark;
import cn.yuanqiao.common.core.context.ResponseUtils;
import cn.yuanqiao.common.core.domain.entity.SysRole;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.common.core.domain.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import static cn.yuanqiao.common.utils.PageUtils.startPage;

/**
 * @author zjj
 * @date 2023/9/12
 */
@Service
public class TenantDownloadRecordSeriveImpl implements TenantDownloadRecordSerive {

    @Autowired
    private TenantDownloadRecordMapper downloadRecordMapper;
    @Autowired
    private TenantCategoryMapper categoryMapper;
    @Autowired
    private TenantYqdaDocumentMapper documentMapper;
    @Autowired
    private IYqSyService yqSyService;
    @Autowired
    private ITenantSysConfigService sysConfigService;

    @Override
    public int insertTenantDownloadRecord(TenantDownloadRecord downloadRecord) {
        LoginUser user = SecurityUtils.getLoginUser();
        downloadRecord.setDownloadUserId(user.getUserId());
        downloadRecord.setCreateTime(new Date());
        return downloadRecordMapper.insertTenantDownloadRecord(downloadRecord);
    }

    @Override
    public int updateTenantDownloadRecord(TenantDownloadRecord downloadRecord) {
        downloadRecord.setCreateTime(new Date());
        return downloadRecordMapper.updateTenantDownloadRecord(downloadRecord);
    }

    @Override
    public List<DownloadRecord> selectDownloadRecord(Long categoryId, Long menuId, String fileName, String userName) {
        LoginUser user = SecurityUtils.getLoginUser();
        String tenantCode = SecurityUtils.getTenantCode();
        List<String> eFileTable = downloadRecordMapper.getEFileTableName(tenantCode,user.getUserId());
        List<DownloadRecord> list = new ArrayList<>();
        if(eFileTable !=null && eFileTable.size()>0){
            StringBuilder col = new StringBuilder(" case ");
            StringBuilder whereCol = new StringBuilder();
            StringBuilder whereFileName = new StringBuilder(" and (");
            for(int i = 0;i<eFileTable.size();i++){
                col.append(" when a"+(i+1)+".doc_id is not null then a"+(i+1)+".doc_name ");
                whereCol.append(" left join "+eFileTable.get(i)+" a"+(i+1)+" on a.doc_id = a"+(i+1)+".doc_id ");
                if(fileName !=null){
                    whereFileName.append(" a"+(i+1)+".DOC_NAME like '%"+fileName+"%' or ");
                }
            }
            col.append(" else '' END AS DOC_NAME");
            whereCol.append("where 1=1 ");
            if(fileName !=null){
                whereCol.append(whereFileName.substring(0,whereFileName.length()-3)).append(")");
            }
            if(categoryId !=null){
                whereCol.append(" and a.CATEGORY_ID = '"+categoryId+"'");
            }
            if(menuId != null){
                whereCol.append(" and a.MENU_ID = '"+menuId+"'");
            }
            if(userName != null){
                whereCol.append(" and c.user_name like '%"+userName+"%'");
            }

           // Boolean isDagly = SecurityUtils.isDagly();
            Long userId = user.getUserId();
//            if(isDagly){
//                userId = null;
//            }
            startPage();
            list = downloadRecordMapper.selectDownloadRecord(tenantCode,userId,col.toString(),whereCol.toString());
        }
        return list;
    }

    @Override
    public void download(Long id,String sydm, HttpServletResponse response) throws Exception{
        TenantDownloadRecord select = new TenantDownloadRecord();
        select.setId(id);
        TenantDownloadRecord downloadRecord = downloadRecordMapper.selectOneDownloadRecordById(select);
        String tenantCode = SecurityUtils.getTenantCode();
        if(downloadRecord.getBorrowId().equals(-1L)){
            //不是借阅下载记录
            Set<String> a = SecurityUtils.getLoginUser().getRoles();
            System.out.println(a);
            List<SysRole> roles = SecurityUtils.getLoginUser().getUser().getRoles();
            if(roles.size()>0){
                StringBuilder roleStr = new StringBuilder();
                for(int i = 0;i<roles.size();i++){
                    roleStr.append(roles.get(i).getRoleId()).append(",");
                }
                roleStr.deleteCharAt(roleStr.length()-1);
                Boolean isDagly = SecurityUtils.isDagly();
                if(isDagly){
                    //有权限下载
                    download(id,downloadRecord.getDocId(),null,downloadRecord.getCategoryId(),sydm,response);
                }
                Integer i = downloadRecordMapper.candownload(tenantCode,downloadRecord.getCategoryId(),downloadRecord.getMenuId(),roleStr.toString());
                if(i>0){
                    //有权限下载
                    download(id,downloadRecord.getDocId(),null,downloadRecord.getCategoryId(),sydm,response);
                }else {
                    throw new ServiceException("您没有权限下载！");
                }
            }
        }else {
            Boolean isDagly = SecurityUtils.isDagly();
            if(isDagly){
                //有权限下载
                download(id,downloadRecord.getDocId(),null,downloadRecord.getCategoryId(),sydm,response);
            }
            //是借阅下载记录
            Integer i = downloadRecordMapper.canBorrowdownload(tenantCode,downloadRecord.getBorrowId());
            if(i>0){
                //有权限下载
                download(id,downloadRecord.getDocId(),null,downloadRecord.getCategoryId(),sydm,response);
            }else {
                throw new ServiceException("您没有权限下载！");
            }
        }
    }

    private void download(Long id,Long doc_id, Long daId, Long categoryId,String sydm, HttpServletResponse response) throws Exception{
        TenantCategory tenantCategory=new TenantCategory();
        String catetablename=tenantCategory.getTableName();
        TenantYqda tenantYqda=new TenantYqda();
        String allftable=tenantYqda.getTableName();
        String efiletable="";
        if(null==daId){
            tenantCategory.setCategoryId(categoryId);
            TenantCategory tenantCategory1 = categoryMapper.selectTenantCategoryList(tenantCategory).get(0);
            efiletable=tenantCategory1.getEfileTableName();
        }else{
            efiletable=documentMapper.gettablenamebydaid(daId,allftable,catetablename);
        }
        TenantYqdaDocument document=documentMapper.selectnameandpathbyDocid(doc_id,efiletable);
        if(document==null){
            throw new ServiceException("文件不存在!");
        }
        String filePath=document.getDocMnt()+ File.separator+document.getPath();
        File f = new File(filePath);
        if (!f.exists()) {
            throw new ServiceException("文件不存在!");
            //response.sendError(404, "File not found!");
            //return ResponseData.error("File not found!");
        }

        if (StringUtils.isNotEmpty(sydm)){
            //添加水印
            YqSy yqSy = new YqSy();
            yqSy.setSydm(sydm);
            yqSy = yqSyService.selectYqSyBySydm(yqSy);
            if (null!=yqSy&&StringUtils.isNotEmpty(yqSy.getSynr())){
                String fpath = f.getPath();
                String fileFullName = fpath.substring(fpath.lastIndexOf("\\")+1,fpath.lastIndexOf("."));
                String prefix=fpath.substring(fpath.lastIndexOf(".")+1);
                String 	waterMarkFilepath = sysConfigService.selectConfigByKey("WATERMARKFILEPATH");
                //生成水印文件地址
                if(!StringUtils.isEmpty(waterMarkFilepath)) {
                    File folder = new File(waterMarkFilepath);
                    if (!folder.exists()) {
                        if (folder.mkdirs()) {

                        }else {
                            throw new RuntimeException("路径"+waterMarkFilepath+"不存在！");
                        }
                    }
                    waterMarkFilepath+=fileFullName+"."+prefix;
                }else {
                    throw new RuntimeException("没有在系统参数表配置添加水印文件保存路径WATERMARKFILEPATH字段");
                }
                if("pdf".equals(prefix.toLowerCase())) {
                    FileWaterMark.pdfWaterMark(fpath,waterMarkFilepath,yqSy);
                    f = new File(waterMarkFilepath);
                } else if ("png".equals(prefix.toLowerCase())||"jpg".equals(prefix.toLowerCase())||"jpeg".equals(prefix.toLowerCase())) {
                    FileWaterMark.addPictureWaterMark(fpath,waterMarkFilepath,yqSy);
                    f = new File(waterMarkFilepath);
                }
            }
        }

        BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
        byte[] buf = new byte[1024];
        int len = 0;
        boolean isOnLine=true;
        response.reset(); // 非常重要
        ResponseUtils.defaultResponse(response);
        String  fileName= document.getDocName();

        if (isOnLine) { // 在线打开方式
            URL u = new URL("file:///" + filePath);
            response.setContentType(u.openConnection().getContentType());
            response.setHeader("Content-Disposition", "inline; filename=" + fileName);
            // 文件名应该编码成UTF-8
        } else { // 纯下载方式
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        }
        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) > 0){
            out.write(buf, 0, len);
        }
        br.close();
        out.close();

        //更新下载记录
        TenantDownloadRecord downloadRecord = new TenantDownloadRecord();
        downloadRecord.setCreateTime(new Date());
        downloadRecord.setId(id);
        downloadRecordMapper.updateTenantDownloadRecord(downloadRecord);
    }
}
